﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MeTalker.Aide;
using MeTalker.SDK.Core;
using MeTalker.Aide.data;
using System.Diagnostics;
using Top.Api.Request;
using Top.Api;
using Top.Api.Response;
using MeTalker.Aide.Mode;
using Top.Api.Domain;
using MeTalker.Window.SDK.Core;

namespace MeTalker.Aide.Forms
{
    internal partial class OrderForm : FormBase
    {
        TalkerForm mainForm;
        int width;
        object obj1 = new object();
        object obj2 = new object();
        string Old_Msg = "";
        bool isHandler = true;
        bool isReplay = true;
        bool flag = false;
        bool isChanage = false;
        string oldRemarks = string.Empty;
        long FlagUp = 1;
        Point point;
        internal bool IsFileNode { get; set; }
        TaobaoHelper taobaoHelper;
        private OrderForm()
        {
            InitializeComponent();
            ToolTip tip = new ToolTip();
            tip.SetToolTip(this.btnLetter, "查询当前客户快件状况");
            tip.SetToolTip(this.btnCheck, "核对当前客户订单与留言");
            tip.SetToolTip(this.btnFind, "根椐当前关键字查询商品链接\r\n关键字请在旺旺窗口回复框输入");
            tip.SetToolTip(this.btnFindOrder, "查询当前客户最近三个月的订单信息");
            tip.SetToolTip(this.btnClear, "清空旺旺窗口回复框");
            lblState.Text = "";
            txtRemarks.TabIndex = 10;
            IsFileNode = true;
            this.groupBox1.Text = "";
            this.Load += new EventHandler(OrderForm_Load);
            this.Click += new EventHandler(OrderForm_Click);
            this.groupBox1.Click += new EventHandler(groupBox1_Click);
            this.txtRemarks.LostFocus += new EventHandler(txtRemarks_LostFocus);
            this.treeView.LostFocus += new EventHandler(treeView_LostFocus);
        }
        public OrderForm(TalkerForm main, string user)
            : this(main)
        {
            this.groupBox1.Text = user;
        }
        public OrderForm(TalkerForm main)
            : this()
        {
            mainForm = main;
            mainForm.OrderCallback = new MessageCallback(MessageCallback);
            mainForm.BorBodyHandler = new BodyHandler(BodyHandler);
            btnRemarks.Enabled = false;
            txtRemarks.Enabled = false;
            var ds = from temp in DataFactory.Accounts where temp.AccountId.Equals(mainForm.Proc.Alias) select temp;
            Account account = ds.FirstOrDefault();
            if (account!=null)
            {
                taobaoHelper = new TaobaoHelper(account);
            }
            else
            {
                ds = from temp in DataFactory.Accounts where temp.Default select temp;
                account = ds.FirstOrDefault();
                if (account != null)
                {
                    taobaoHelper = new TaobaoHelper(account);
                }
                else
                {
                }
            }
        }

        void treeView_LostFocus(object sender, EventArgs e)
        {
        }

        void txtRemarks_LostFocus(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.groupBox1.Text))
            {
                DataList dataList = DataFactory.DataList;
                var ds = from temp in dataList.Nodes where temp.DateType == DataType.Remarks && temp.Recorder != null && temp.Recorder.Equals(this.groupBox1.Text) select temp;
                Data data = ds.FirstOrDefault();

                if (data != null)
                {
                    data.Key = DataFactory.KEY_DTAT_AUTO;
                    data.Recorder = this.groupBox1.Text;
                    data.Alias = mainForm.Proc.Alias;
                    data.Receiver = mainForm.Proc.Account;
                    data.Keyword = "";
                    data.Text = txtRemarks.Text;
                    data.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    data.DateType = DataType.Remarks;
                }
                else
                {
                    data = new Data();
                    data.Alias = mainForm.Proc.Alias;
                    data.Receiver = mainForm.Proc.Account;
                    data.Key = DataFactory.KEY_DTAT_AUTO;
                    data.Recorder = this.groupBox1.Text;
                    data.Keyword = "";
                    data.Text = txtRemarks.Text;
                    data.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    data.DateType = DataType.Remarks;
                    dataList.Nodes.Add(data);
                }
            }
        }

        #region 增加列表

        //string oldMsg = string.Empty;
        //bool isOp = false;
        delegate void SetListViewHandler(List<Record> msgs);
        delegate void SetTreeViewAppendHandler(Record msgs);

        void SetTreeView(List<Record> msgs)
        {
            SetListViewHandler del = delegate(List<Record> msgs1)
            {
                try
                {
                    treeView.Nodes.Clear();
                    if (msgs != null)
                    {
                        int i = 1;
                        foreach (var temp in msgs)
                        {
                            string msg = temp.Text;
                            int leftIndex = msg.IndexOf(UtilHelper.FAST_LEFT_SYMBOL);
                            int rightIndex = msg.IndexOf(UtilHelper.FAST_RIGHT_SYMBOL);
                            if (leftIndex == 0 && rightIndex > 0)
                            {
                                msg = msg.Substring(rightIndex + 1, msg.Length - (rightIndex + 1));
                            }
                            TreeNode node = new TreeNode(i + ". " + msg);
                            node.ToolTipText = msg;
                            treeView.Nodes.Add(node);
                            i++;
                            if (i > DataFactory.SystemConfig.Line)
                                break;
                        }
                    }
                }
                catch { }
            };
            this.treeView.BeginInvoke(del, new object[] { msgs });
        }

        void SetTreeViewAppend(Record msgs)
        {
            SetTreeViewAppendHandler del = delegate(Record msgs1)
            {
                try
                {
                    if (msgs != null)
                    {
                        string msg = msgs.Text;
                        int leftIndex = msg.IndexOf(UtilHelper.FAST_LEFT_SYMBOL);
                        int rightIndex = msg.IndexOf(UtilHelper.FAST_RIGHT_SYMBOL);
                        if (leftIndex == 0 && rightIndex > 0)
                        {
                            msg = msg.Substring(rightIndex + 1, msg.Length - (rightIndex + 1));
                        }
                        TreeNode node = new TreeNode(treeView.Nodes.Count + ". " + msg);
                        node.ToolTipText = msg;
                        treeView.Nodes.Add(node);                 
                    }
                }
                catch { }
            };
            this.treeView.BeginInvoke(del, new object[] { msgs });
        }

        #endregion

        void BodyHandler(object sender, MessageBody msgBody)
        {
            try
            {
                if (!msgBody.SendName.Equals(mainForm.Proc.Alias))
                {
                    lock (obj1)
                    {
                        isHandler = true;
                    }

                    #region 自动回复
                    if (DataFactory.SystemConfig.IsAutoReply)
                    {
                        string text = UtilHelper.FindAnswer(msgBody.Content);
                        if (!string.IsNullOrEmpty(text))
                        {
                            mainForm.SendText(text);
                            return;
                        }
                    }
                    #endregion

                    List<Record> temp1 = UtilHelper.FindLinkAnswer(msgBody.Content);
                    SetTreeView(temp1);
                }
                flag = true;
            }
            catch { }
        }

        void MessageCallback(object sender, string msg)
        {
            try
            {
                if (Old_Msg.Equals(msg))
                {
                    return;
                }
                isReplay = false;
                lock (obj1)
                {
                    if (isHandler)
                    {
                        List<Record> temp1 = UtilHelper.FindMessages(msg);
                        if (temp1.Count > 0)
                            SetTreeView(temp1);
                        isHandler = false;
                        return;
                    }
                }

                lock (obj2)
                {
                    Old_Msg = msg;
                    string msg1 = UtilHelper.FormatMessage(msg);
                    if (msg1.Length >= 3)
                    {
                        #region 快捷回复 ,.
                        int index = msg1.IndexOf(UtilHelper.IME_REPLY);
                        int idNum = -1;
                        if (index >= 0)
                        {
                            int len = msg1.Length;
                            if (len >= (index + UtilHelper.IME_REPLY.Length + 1))
                            {
                                string str1 = msg1.Substring(index, len - index);
                                if (int.TryParse(msg1[index + 2] + "", out idNum))
                                {
                                    foreach (TreeNode node in treeView.Nodes)
                                    {
                                        if (node.Text[0] == msg1[index + 2])
                                        {
                                            string ss = node.Text.Substring(3, node.Text.Length - 3);
                                            mainForm.SendText(msg1.Replace(str1, ss));
                                            mainForm.SendText(ss);
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    List<Record> recordTemps = null;
                                    string str2 = msg1.Substring(index + 2, (msg1.Length - index - 2));
                                    string findStr = (UtilHelper.FAST_LEFT_SYMBOL + str2 + UtilHelper.FAST_RIGHT_SYMBOL);
                                    string findStr1 = (UtilHelper.FAST_LEFT_SYMBOL + str2);
                                    #region 2011-10-11新加

                                    if (recordTemps == null)
                                        recordTemps = new List<Record>();
                                    recordTemps.AddRange(UtilHelper.FindFastMessages(str2));
                                    #endregion

                                    
                                  

                                    var ds3 = from temp in DataFactory.DataList.Nodes where temp.Text.Contains(str2) select temp;
                                    foreach (var dd in ds3)
                                    {
                                        if (recordTemps == null)
                                            recordTemps = new List<Record>();
                                        recordTemps.Add(new Record() { Text = dd.Text });
                                    }

                                    foreach (var ds2 in DataFactory.NodeLists.Nodes)
                                    {
                                        var ds1 = from temp in ds2.SubNode where temp.Text.Contains(str2) select temp;
                                        foreach (var dd in ds1)
                                        {
                                            if (recordTemps == null)
                                                recordTemps = new List<Record>();
                                            recordTemps.Add(new Record() { Text = dd.Text });
                                        }
                                    }
                                    if (recordTemps != null && recordTemps.Count == 1)
                                    {
                                        string msgTemp = recordTemps[0].Text;
                                        if (msgTemp.Contains(findStr))
                                        {
                                            string sendmsg = msgTemp.Replace(findStr, "");
                                            mainForm.SendText(sendmsg);
                                            return;
                                        }
                                        else
                                        {
                                            mainForm.SendText(msgTemp);
                                            return;
                                        }
                                    }

                                    else if (recordTemps != null && recordTemps.Count > 1)
                                    {
                                        SetTreeView(recordTemps);
                                        return;
                                    }
                                    else
                                    {
                                    }
                                }
                            }
                        }
                        #endregion

                        #region 快捷回复 ,,
                        index = msg1.IndexOf(UtilHelper.IME_SET);
                        if (index >= 0)
                        {
                            int len = msg1.Length;
                            if (len >= (index + UtilHelper.IME_SET.Length + 1))
                            {
                                string str1 = msg1.Substring(index, len - index);
                                bool flag = int.TryParse(msg1[index + 2] + "", out idNum);
                                if (flag)
                                {
                                    foreach (TreeNode node in treeView.Nodes)
                                    {
                                        if (node.Text[0] == msg1[index + 2])
                                        {
                                            string ss = node.Text.Substring(3, node.Text.Length - 3);
                                            mainForm.SetText(ss);
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    List<Record> recordTemps = null;
                                    string str2 = msg1.Substring(index + 2, msg1.Length - index - 2);
                                    string findStr = (UtilHelper.FAST_LEFT_SYMBOL + str2 + UtilHelper.FAST_RIGHT_SYMBOL);
                                    string findStr1 = (UtilHelper.FAST_LEFT_SYMBOL + str2);
                                    //查找短语
                                    if (recordTemps == null)
                                        recordTemps = new List<Record>();
                                    recordTemps.AddRange(UtilHelper.FindFastMessages(str2));
                                    var ds3 = from temp in DataFactory.DataList.Nodes where temp.Text.Contains(str2) select temp;
                                    foreach (var dd in ds3)
                                    {
                                        if (recordTemps == null)
                                            recordTemps = new List<Record>();
                                        recordTemps.Add(new Record() { Text = dd.Text });
                                    }

                                    foreach (var ds2 in DataFactory.NodeLists.Nodes)
                                    {
                                        var ds1 = from temp in ds2.SubNode where temp.Text.Contains(str2) select temp;
                                        foreach (var dd in ds1)
                                        {
                                            if (recordTemps == null)
                                                recordTemps = new List<Record>();
                                            recordTemps.Add(new Record() { Text = dd.Text });
                                        }
                                    }
                                    if (recordTemps != null && recordTemps.Count == 1)
                                    {
                                        string msgTemp = recordTemps[0].Text;
                                        if (msgTemp.Contains(findStr))
                                        {
                                            string sendmsg = msgTemp.Replace(findStr, "");
                                            mainForm.SetText(sendmsg);
                                            return;
                                        }
                                        else
                                        {
                                            mainForm.SetText(msgTemp);
                                            return;
                                        }
                                    }
                                    else if (recordTemps != null && recordTemps.Count > 1)
                                    {
                                        SetTreeView(recordTemps);
                                        return;
                                    }
                                    else
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    FindChatAndShortMsg(msg, msg1);
                }
            }
            catch { }
        }

        void FindChatAndShortMsg(string msg, string msg1)
        {
            #region 查找以前说过的话
            
            //最后为标点时
            if (msg1.EndsWith(",") || msg1.EndsWith("，"))
            {
                return;
            }
            if (msg1.Contains(",.") || msg1.Contains(",,"))
            {
                return;
            }
            if (!string.IsNullOrEmpty(msg))
            {
                //查找短语
                List<Record> records = UtilHelper.FindMessages(msg);
                //查找聊天记录
                var ds = from temp in DataFactory.ChatRecords.Records where temp.Text.Contains(msg) && temp.DateType == DataType.Send select temp;
           
                records.AddRange(ds);
                SetTreeView(records);
            }

            #endregion
        
        }

        void groupBox1_Click(object sender, EventArgs e)
        {
            WindowControl.SetForegroundWindow(mainForm.Handle);
            WindowControl.SetForegroundWindow(mainForm.helper.HandleWinForm);
        }

        void OrderForm_Click(object sender, EventArgs e)
        {
            WindowControl.SetForegroundWindow(mainForm.Handle);
            WindowControl.SetForegroundWindow(mainForm.helper.HandleWinForm);
        }

        void OrderForm_Load(object sender, EventArgs e)
        {
            SetLocation(point, width, UtilHelper.MAX_ORDER_HEIGHT);
            timer1.Interval = 1000;
            timer1.Enabled = true;
        }

        internal void SetLocation(int x, int y, int cx, int cy)
        {
            SetLocation(new Point(x, y), cx, cy);
        }

        internal void SetLocation(Point point, int cx, int cy)
        {
            lock (this)
            {
                width = cx;
                this.point = point;
                if (point.X != Location.X || point.Y != Location.Y)
                {
                    this.Location = point;
                    isChanage = true;
                }
                if (this.Width != cx + 1)
                {
                    this.Width = cx + 1;
                    isChanage = true;
                }
                if (UtilHelper.MAX_ORDER_HEIGHT != this.Height)
                {
                    this.Height = UtilHelper.MAX_ORDER_HEIGHT;
                    isChanage = true;
                }
                isChanage = false;
            }
        }
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!this.groupBox1.Text.Equals(mainForm.SelectUser) && !string.IsNullOrEmpty(mainForm.SelectUser) && mainForm.SelectUser.Length<=30)
                {
                    this.groupBox1.Text = mainForm.SelectUser;
                    string buynick = this.groupBox1.Text;
                    txtRemarks.Text = "";
                    txtUpload.Text = "";
                    btnUpload.Enabled = false;
                    txtUpload.Enabled = false;
                    DataList dataList = DataFactory.DataList;
                    var ds = from temp in dataList.Nodes where temp.DateType == DataType.Remarks && temp.Recorder != null && temp.Recorder.Equals(buynick) select temp;
                    Data data = ds.FirstOrDefault();
                    if (data != null && !string.IsNullOrEmpty(data.Text) && !data.Text.Equals(oldRemarks))
                    {
                        oldRemarks = data.Text;
                        txtRemarks.Text = data.Text;
                        txtRemarks.SelectionLength = oldRemarks.Length;
                        txtRemarks.SelectionStart = 0;
                        txtRemarks.ScrollToCaret();
                        txtRemarks.SelectNextControl(this.btnClear, true, false, false, false);
                    }

                    if (taobaoHelper != null)
                    {
                        btnUpload.Enabled = true;
                        txtUpload.Enabled = true;
                        var dsresp = from temp in DataFactory.Trades.TradeFulls where temp.Trade.BuyerNick.Equals(buynick) select temp;
                        TradeFullinfoGetResponse dataTemp = dsresp.FirstOrDefault();
                        if (dataTemp != null)
                        {
                            txtUpload.Text = dataTemp.Trade.SellerMemo.Replace("\n", "\r\n");
                        }
                    }
                }
                if (!string.IsNullOrEmpty(this.groupBox1.Text))
                {
                    btnRemarks.Enabled = true; txtRemarks.Enabled = true;
                }
                else { btnRemarks.Enabled = false; txtRemarks.Enabled = false; }
            }
            catch { }
        }

        void MemoFlag(bool flag1)
        {
            try
            {
                if (string.IsNullOrEmpty(txtUpload.Text))
                {
                    MeMessageBox.ShowInformation("备忘不能为空!");
                    return;
                }
                string buynick = this.groupBox1.Text;
                bool updateFlag = false;
                string memo = string.Empty;
                if (DataFactory.SystemConfig.IsAutoAddAccount)
                {
                    memo += mainForm.WorkProcess.Account + Environment.NewLine;
                }
                if (DataFactory.SystemConfig.IsAutoAddCurrDate)
                {
                    memo += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
                }
                TradeFullinfoGetResponse tempresp = null;
                if (taobaoHelper != null)
                {
                    tempresp = taobaoHelper.FindOrderMemo(buynick);
                    memo += txtUpload.Text;
                    if (tempresp != null && flag1)
                    {
                        updateFlag = taobaoHelper.UpdateMemo(tempresp.Trade.Tid, FlagUp, false, memo);
                    }
                    else if (tempresp != null && DataFactory.SystemConfig.IsRemarkAppend)
                    {
                        memo += tempresp.Trade.SellerMemo + Environment.NewLine + memo + Environment.NewLine;
                        updateFlag = taobaoHelper.UpdateMemo(tempresp.Trade.Tid, FlagUp, false, memo);
                    }
                    else
                    {
                        MeMessageBox.ShowInformation(string.Format("[{0}]最近三个月没有订单!", buynick));
                        return;
                    }
                }
                if (updateFlag)
                {
                    var ds = from temp in DataFactory.Trades.TradeFulls where temp.Trade.BuyerNick.Equals(buynick) select temp;
                    TradeFullinfoGetResponse d = ds.FirstOrDefault();
                    if (d != null)
                        d.Trade.SellerMemo = memo;
                    else
                    {
                        DataFactory.Trades.TradeFulls.Add(new TradeFullinfoGetResponse() { Trade = new Trade() { BuyerNick = buynick, SellerMemo = memo, SellerNick = mainForm.WorkProcess.Alias } });
                    }
                    MeMessageBox.ShowInformation("上传备忘成功!");
                }
                else
                {
                    MeMessageBox.ShowInformation("上传备忘失败!");
                }
            }
            catch { }
        }
  
        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FlagUp = 1;
            MemoFlag(true);
        }

        private void ToolStripMenuItem0_Click(object sender, EventArgs e)
        {
            FlagUp = 0;
            ToolStripMenuItem0.Checked = true;
            ToolStripMenuItem1.Checked = false;
            ToolStripMenuItem2.Checked = false;
            ToolStripMenuItem3.Checked = false;
            ToolStripMenuItem4.Checked = false;
            ToolStripMenuItem5.Checked = false;
            btnUpload.Image = ToolStripMenuItem0.Image;
        }

        private void ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FlagUp = 1;
            ToolStripMenuItem0.Checked = false;
            ToolStripMenuItem1.Checked = true;
            ToolStripMenuItem2.Checked = false;
            ToolStripMenuItem3.Checked = false;
            ToolStripMenuItem4.Checked = false;
            ToolStripMenuItem5.Checked = false;
            btnUpload.Image = ToolStripMenuItem1.Image;
        }

        private void ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            FlagUp = 2;
            ToolStripMenuItem0.Checked = false;
            ToolStripMenuItem1.Checked = false;
            ToolStripMenuItem2.Checked = true;
            ToolStripMenuItem3.Checked = false;
            ToolStripMenuItem4.Checked = false;
            ToolStripMenuItem5.Checked = false;
            btnUpload.Image = ToolStripMenuItem2.Image;
        }

        private void ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            FlagUp = 3;
            ToolStripMenuItem0.Checked = false;
            ToolStripMenuItem1.Checked = false;
            ToolStripMenuItem2.Checked = false;
            ToolStripMenuItem3.Checked = true;
            ToolStripMenuItem4.Checked = false;
            ToolStripMenuItem5.Checked = false;
            btnUpload.Image = ToolStripMenuItem3.Image;
        }

        private void ToolStripMenuItem4_Click(object sender, EventArgs e)
        {
            FlagUp = 4;
            ToolStripMenuItem0.Checked = false;
            ToolStripMenuItem1.Checked = false;
            ToolStripMenuItem2.Checked = false;
            ToolStripMenuItem3.Checked = false;
            ToolStripMenuItem4.Checked = true;
            ToolStripMenuItem5.Checked = false;
            btnUpload.Image = ToolStripMenuItem4.Image;
        }

        private void ToolStripMenuItem5_Click(object sender, EventArgs e)
        {
            FlagUp = 5;
            ToolStripMenuItem0.Checked = false;
            ToolStripMenuItem1.Checked = false;
            ToolStripMenuItem2.Checked = false;
            ToolStripMenuItem3.Checked = false;
            ToolStripMenuItem4.Checked = false;
            ToolStripMenuItem5.Checked = true;
            btnUpload.Image = ToolStripMenuItem5.Image;
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            MemoFlag(false);
        }

        private void btnRemarks_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.groupBox1.Text)) { return; }
            DataList dataList = DataFactory.DataList;
            var ds = from temp in dataList.Nodes where temp.DateType == DataType.Remarks && temp.Recorder != null && temp.Recorder.Equals(this.groupBox1.Text) select temp;
            Data data = ds.FirstOrDefault();
            if (data != null)
            {
                string msg = data.Text + "\r\n记录者:" + data.Alias + " 记录时间:" + data.Time;
                new frmRemarks(this.groupBox1.Text, msg).Show(); ;
            }
        }

        private void btnFindOrder_Click(object sender, EventArgs e)
        {
            string url = UtilHelper.TAOBAO_QUERY_ORDER_URL + this.groupBox1.Text;
            RunBrowser(url);
        }

        void RunBrowser(string url)
        {
            try
            {
                if (DataFactory.SystemConfig.IsUsezBrowser)
                {
                    Process.Start("zbrowser.exe", url);
                }
                else
                {
                    Process.Start(url);
                }
            }
            catch
            {
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (mainForm != null)
            {
                mainForm.SetForegroundMainWindow();
                mainForm.SendMessage(mainForm.helper.HandleMessageBody, 177, 0, -1);
                mainForm.SendMessage(mainForm.helper.HandleMessageBody, 771, 0, -1);
            }
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
        }

        private void treeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {

        }

        private void treeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (e.Node != null && e.Node.Nodes != null && e.Node.Nodes.Count == 0)
                {
                    string msg = e.Node.Text;
                    if (msg.Length > 3)
                    {
                        isHandler = false;

                        string sendMsg = msg.Substring(3, msg.Length - 3);
                        if (sendMsg.Contains(UtilHelper.FAST_LEFT_SYMBOL) && sendMsg.Contains(UtilHelper.FAST_RIGHT_SYMBOL) && sendMsg.IndexOf(UtilHelper.FAST_LEFT_SYMBOL) == 0) {
                            int index = sendMsg.IndexOf(UtilHelper.FAST_RIGHT_SYMBOL);
                            sendMsg = sendMsg.Substring(index);
                        }
                        mainForm.SendText(sendMsg);
                    }
                }
            }
        }

        private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (e.Node != null && e.Node.Nodes != null && e.Node.Nodes.Count == 0)
                {
                    string msg = e.Node.Text;
                    if (msg.Length > 3)
                    {
                        isHandler = false;
                        string sendMsg = msg.Substring(3, msg.Length - 3);
                        if (sendMsg.Contains(UtilHelper.FAST_LEFT_SYMBOL) && sendMsg.Contains(UtilHelper.FAST_RIGHT_SYMBOL) && sendMsg.IndexOf(UtilHelper.FAST_LEFT_SYMBOL) == 0)
                        {
                            int index = sendMsg.IndexOf(UtilHelper.FAST_RIGHT_SYMBOL);
                            sendMsg = sendMsg.Substring(index);
                        }
                        mainForm.SetText(sendMsg);
                    }
                }
            }
        }

        private void OrderForm_Activated(object sender, EventArgs e)
        {
            mainForm.SetActivated();
        }
        
        private void ToolStripMenuItemWaitPay_Click(object sender, EventArgs e)
        {
            string url = UtilHelper.TAOBAO_QUERY_ORDER_WAIT_PAYMENT_URL + this.groupBox1.Text;
            RunBrowser(url);
        }

        private void ToolStripMenuItemDelivery_Click(object sender, EventArgs e)
        {
            string url = UtilHelper.TAOBAO_QUERY_ORDER_WAIT_DELIVERY_URL + this.groupBox1.Text;
            RunBrowser(url);
        }

        private void ToolStripMenuItemOrder_Click(object sender, EventArgs e)
        {
            btnFindOrder_Click(this, EventArgs.Empty);
        }
        
        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                btnFind.Enabled = false;
                if (taobaoHelper == null)
                {
                    //DialogResult dialogResult = new frmAddLicense(mainForm.WorkProcess.Account).ShowDialog();
                    //if (dialogResult != DialogResult.Yes)
                    //{
                    //    return;
                    //}
                    if (!OpenAddLicense())
                    {
                        return;
                    }
                    var ds = from temp in DataFactory.Accounts where temp.Default select temp;
                    Account account = ds.FirstOrDefault();
                    if (account != null)
                        taobaoHelper = new TaobaoHelper(account);
                }

                string keyword = mainForm.GetReplyMessage();
                if (!string.IsNullOrEmpty(keyword))
                {
                    lblState.Text = "正在查找链接...";
                    string[] msgs = keyword.Split(' ');

                    List<Record> records = new List<Record>();

                    if (msgs.Length == 1)
                    {
                        var ds = from temp in taobaoHelper.GoodsItemsList.Items where temp.Title.ToLower().Contains(keyword.ToLower()) select temp;
                        foreach (var item in ds)
                        {
                            records.Add(SetLinkText(item));
                        }
                    }
                    else if (msgs.Length == 2)
                    {
                        #region 两个
                        char ch = msgs[1][0];
                        string title = msgs[0].ToLower();
                        double price;
                        bool flag = double.TryParse(msgs[1].Substring(1, msgs[1].Length - 1), out price);
                        if (!flag)
                        {
                            MeMessageBox.ShowInformation("输入价格错误");
                            return;
                        }
                        if (ch.Equals('='))
                        {
                            var ds = from temp
                                     in taobaoHelper.GoodsItemsList.Items
                                     where temp.Title.ToLower().Contains(title)
                                     select temp;
                            foreach (var item in ds)
                            {
                                if (double.Parse(item.Price) == price)
                                {
                                    records.Add(SetLinkText(item));
                                }
                            }
                        }
                        else if (ch.Equals('>'))
                        {
                            var ds = from temp
                                         in taobaoHelper.GoodsItemsList.Items
                                     where temp.Title.ToLower().Contains(title)
                                     select temp;
                            foreach (var item in ds)
                            {
                                if (double.Parse(item.Price) > price)
                                {
                                    records.Add(SetLinkText(item));
                                }
                            }

                        }
                        else if (ch.Equals('<'))
                        {
                            var ds = from temp
                                         in taobaoHelper.GoodsItemsList.Items
                                     where temp.Title.ToLower().Contains(title) && double.Parse(temp.Price) < price
                                     select temp;
                            foreach (var item in ds)
                            {
                                records.Add(SetLinkText(item));
                            }

                        }
                        #endregion
                    }
                    else if (msgs.Length == 3)
                    {
                        #region 三个
                        char chStart = msgs[1][0];
                        char chEnd = msgs[2][0];
                        double price1;
                        double price2;
                        bool flag1 = double.TryParse(msgs[1].Substring(1, msgs[1].Length - 1), out price1);
                        bool flag2 = double.TryParse(msgs[2].Substring(1, msgs[2].Length - 1), out price2);
                        if (!flag1 || !flag2)
                        {
                            MeMessageBox.ShowInformation("输入价格错误");
                            return;
                        }
                        if (chStart.Equals('<') && chEnd.Equals('>'))
                        {
                            var ds = from temp
                                     in taobaoHelper.GoodsItemsList.Items
                                     where temp.Title.ToLower().Contains(msgs[0].ToLower()) && double.Parse(temp.Price) < price1 && double.Parse(temp.Price) > price2
                                     select temp;
                            foreach (var item in ds)
                            {
                                records.Add(SetLinkText(item));
                            }
                        }
                        #endregion
                    }
                    this.SetTreeView(records);
                }
                else
                {
                    MeMessageBox.ShowInformation("请在旺旺回复框输入商品关键字，这样才能得到相应的链接");
                }
            }
            catch { }
            finally {
                btnFind.Enabled = true;
                lblState.Text = "";
            }
        }

        Record SetLinkText(Item item)
        {
            return new Record() { Text = "商品名=" + item.Title + ",价格=" + item.Price + ",链接=" + item.DetailUrl };
        }

        private void ToolStripMenuItemRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                btnFind.Enabled = false;
                lblState.Text = "正在更新链接...";
                if (taobaoHelper != null)
                    taobaoHelper.QueryItem();
            }
            catch { }
            finally {
                btnFind.Enabled = true;
                lblState.Text = "";
            }
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                btnCheck.Enabled = false;
                if (taobaoHelper == null)
                {
                    //DialogResult dialogResult = new frmAddLicense(mainForm.WorkProcess.Account).ShowDialog();
                    //if (dialogResult != DialogResult.Yes)
                    //{
                    //    return;
                    //}
                    if (!OpenAddLicense())
                    {
                        return;
                    }
                    var ds = from temp in DataFactory.Accounts where temp.Default select temp;
                    Account account = ds.FirstOrDefault();
                    if (account != null)
                        taobaoHelper = new TaobaoHelper(account);
                }

                if (taobaoHelper != null)
                {
                    if (!string.IsNullOrEmpty(this.groupBox1.Text))
                    {
                        lblState.Text = "正在核对[" + this.groupBox1.Text + "]";
                        string msg = taobaoHelper.FindOrderZipCode(this.groupBox1.Text);
                        if (!string.IsNullOrEmpty(msg))
                        {
                            msg = DataFactory.SystemConfig.CheckSalutation + Environment.NewLine + msg;
                            if (DataFactory.SystemConfig.IsCheckSendExpress)
                            {
                                Send(mainForm.helper.HandleMessageBody, msg);
                            }
                            else {
                                KeysetControl.SendMessageText(mainForm.helper.HandleMessageBody, msg);
                            }
                        }
                    }
                    else
                    {
                        MeMessageBox.ShowInformation("当前没有检测到客户!");
                    }
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("查件", ex);
            }
            finally {
                btnCheck.Enabled = true;
                lblState.Text = "";
            }
        }

        internal void Send(IntPtr intptr, string msg)
        {
            KeysetControl.SendMessage(intptr, 177, 0, -1);//全选

            KeysetControl.SendMessageText(intptr, msg);
            WindowControl.SetForegroundWindow(intptr);
            //SendKeys.Send("~");
            KeysetControl.keybd_event(13, 0, 0, 0);
        }

        bool OpenAddLicense() {
            DialogResult dialogResult = new frmAddLicense(mainForm.WorkProcess.Account).ShowDialog();
            if (dialogResult != DialogResult.Yes)
            {
                return false;
            }
            SerializerFactory.ToAppKeyFile();
            return true;
        }

        private void btnLetter_Click(object sender, EventArgs e)
        {
            try
            {
                btnLetter.Enabled = false;
                if (taobaoHelper == null)
                {
                    if (!OpenAddLicense()) {
                        return;
                    }
                    //DialogResult dialogResult = new frmAddLicense(mainForm.WorkProcess.Account).ShowDialog();
                    //if (dialogResult != DialogResult.Yes)
                    //{
                    //    return;
                    //}
                    var ds = from temp in DataFactory.Accounts where temp.Default select temp;
                    Account account = ds.FirstOrDefault();
                    if (account != null)
                        taobaoHelper = new TaobaoHelper(account);
                }

                if (taobaoHelper != null)
                {
                    if (!string.IsNullOrEmpty(this.groupBox1.Text))
                    {
                        lblState.Text = "正在查件[" + this.groupBox1.Text + "]";
                        string msg = taobaoHelper.FindOrderTrack(this.groupBox1.Text);
                        if (!string.IsNullOrEmpty(msg))
                        {
                            msg = DataFactory.SystemConfig.QuerySalutation + Environment.NewLine + msg;
                            if (DataFactory.SystemConfig.IsQuerySendExpress)
                            {
                                Send(mainForm.helper.HandleMessageBody, msg);
                            }
                            else
                            {
                                KeysetControl.SendMessageText(mainForm.helper.HandleMessageBody, msg);
                            }
                        }
                        else
                        {
                            KeysetControl.SendMessageText(mainForm.helper.HandleMessageBody, DataFactory.SystemConfig.NotQuerySalutation);
                        }
                    }
                    else
                    {
                        MeMessageBox.ShowInformation("当前没有检测到客户!");
                    }
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("查件", ex);
            }
            finally {
                btnLetter.Enabled = true;
                lblState.Text = "";
            }
        }

        private void ToolStripMenuItemMemo_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.groupBox1.Text))
            {
                MeMessageBox.ShowInformation("未检测到客户帐号!");
                return;
            }
            string buynick = this.groupBox1.Text;
            TradeFullinfoGetResponse resp = taobaoHelper.FindOrderMemo(buynick);
            if (resp != null && !resp.IsError)
            {
                string memo = resp.Trade.SellerMemo;
                txtUpload.Text = memo.Replace("\n", "\r\n");
                var ds = from temp in DataFactory.Trades.TradeFulls where temp.Trade.BuyerNick.Equals(buynick) select temp;
                TradeFullinfoGetResponse respTemp = ds.FirstOrDefault();
                if (respTemp != null && respTemp.Trade != null)
                {
                    respTemp.Trade.SellerMemo = memo;
                }
                else
                {
                    DataFactory.Trades.TradeFulls.Add(resp);
                }
            }
            else
            {
                MeMessageBox.ShowInformation(string.Format("[{0}]客户没有备忘", buynick));
                txtUpload.Text = "";
            }
        }
    }
}